package api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"guard/internal/app/admin/models"
	"guard/internal/errors"
	"guard/internal/request"
	"guard/internal/result"
	"net/http"
)

func clientPage(c *gin.Context) {

	// 使用这个绑定，直接报错
	var rp request.Page
	err := c.ShouldBindQuery(&rp)

	if err != nil {
		_ = c.Error(errors.OtherError("错误的分页信息"))
		return
	}

	clientPageObj, err := adminService.ClientPage(rp.Page, rp.PageSize)
	if err != nil {
		_ = c.Error(err)
		return
	}

	c.JSON(http.StatusOK, result.BuildPage{
		Code:  200,
		Msg:   "成功",
		Total: clientPageObj.Total,
		Data:  clientPageObj.Data,
	})
}

func queryClient(c *gin.Context) {

	query := c.Param("query")

	if query == "" || len(query) == 0 {
		_ = c.Error(errors.OtherError("查询条件错误"))
		return
	}

	clientInfo, err := adminService.QueryClient(query)
	if err != nil {
		_ = c.Error(err)
		return
	}

	c.JSON(http.StatusOK, result.Build{
		Code: 200,
		Msg:  "ok",
		Data: clientInfo,
	})
}

func addClient(c *gin.Context) {

	var ci models.ClientDto
	err := c.ShouldBindJSON(&ci)
	if err != nil {
		fmt.Println(err)
		_ = c.Error(errors.OtherError("客户端信息错误"))
		return
	}

	err = adminService.AddClient(ci.Serialization())
	if err != nil {
		_ = c.Error(err)
		return
	}

	c.JSON(http.StatusOK, result.Build{
		Code: 200,
		Msg:  "添加成功",
		Data: nil,
	})
}

func removeClient(c *gin.Context) {

	ci := c.Param("client_id")

	if ci == "" || len(ci) == 0 {
		_ = c.Error(errors.OtherError("客户端ID错误"))
		return
	}

	err := adminService.RemoveClient(ci)
	if err != nil {
		_ = c.Error(err)
		return
	}

	c.JSON(http.StatusOK, result.Build{
		Code: 200,
		Msg:  "删除成功",
		Data: nil,
	})
}
